package com.efounder.form.comp.commodity;

import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.builder.base.data.DataSetEvent;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.data.ESPRowSet;
import com.efounder.form.base.DataComponent;
import com.efounder.form.comp.FormImage;
import com.efounder.form.comp.FormLabel;
import com.efounder.form.comp.FormParabolaAnimation;
import com.efounder.form.model.Column;
import com.efounder.form.model.ColumnGroup;
import com.efounder.form.model.ColumnModel;
import com.efounder.form.model.MDModel;
import com.efounder.form.model.ShoppingCarFormModel;
import com.efounder.frame.arcmenu.ArcMenu;
import com.efounder.frame.widget.EFArcMenuSuperScriptItem;
import com.efounder.mobilecomps.R;
import com.efounder.utils.ResStringUtil;

import java.util.List;
import java.util.Map;

/**
 * Created by XinQing on 2016/9/13.
 * 第三步: 实例化上述定义的实体类,根据自己的需要可以实例化一个或多个，并将它们添加到List集合当中;
 第四步: 定义自己Adapter并集成BaseAdapter, 重写其中的方法。这是最关键的一步，也是难度最大的一步, 具体示例代码及其注释(不要着急，请细细看其中的注释)如下：

 */

public class CommodityCategoryAdapter extends RecyclerView.Adapter {
    // 标题类型
    private static final int TYPE_CATEGORY_ITEM = 0;
    // 子项类型
    private static final int TYPE_ITEM = 1;
    // 类别集合
//    private List<EFDataSet> dataSetList;
    //层级DataSet
    private EFDataSet hierarchyDataSet;
    // 布局填充器
    private LayoutInflater mInflater;
    //列模型
    private Commodity commodity;

    public CommodityCategoryAdapter(Commodity commodity, MDModel formModel) {
        this.commodity = commodity;
        mInflater = LayoutInflater.from(commodity.getContext());
        if (formModel == null) return;
        if (formModel.getMdmDataModel() == null) return;
        Map<String, EFDataSet> dataSetMap = formModel.getMdmDataModel().getDataSetMap();
        if (dataSetMap == null) return;
        hierarchyDataSet = dataSetMap.get(commodity.getDataSetID());
    }

    public void reloadData(MDModel formModel){
        if (formModel == null) return;
        if (formModel.getMdmDataModel() == null) return;
        Map<String, EFDataSet> dataSetMap = formModel.getMdmDataModel().getDataSetMap();
        if (dataSetMap == null) return;
        hierarchyDataSet = dataSetMap.get(commodity.getDataSetID());
        notifyDataSetChanged();
    }

    /**
     * 获取Item的类别，也即确定是子项还是标题项
     */
    @Override
    public int getItemViewType(int position) {
        // 异常情况处理
        if (null == hierarchyDataSet || position < 0 || position > getItemCount()) {
            return TYPE_ITEM;
        }
        // 初始遍历位置
        int categoryFirstIndex = 0;
        // 遍历实体类集合
        List<ESPRowSet> oneLevelRowSetList = hierarchyDataSet.getRowSetList();
        if (oneLevelRowSetList == null ) return TYPE_ITEM;
        for (ESPRowSet espRowSet : oneLevelRowSetList) {
            EFRowSet oneLevelRowSet = (EFRowSet) espRowSet;
            Map<String, EFDataSet> twoLevelDataSetMap = oneLevelRowSet.getDataSetMap();
            if (twoLevelDataSetMap == null || twoLevelDataSetMap.size() == 0) continue;
            //取出twoLevelDataSetMap中唯一的DataSet
            EFDataSet twoLevelDataSet = twoLevelDataSetMap.get(twoLevelDataSetMap.keySet().iterator().next());
            int size = CommodityDataManager.getItemCount(twoLevelDataSet);
            // 在当前分类中的索引值
            int categoryIndex = position - categoryFirstIndex;
            // 如果是首项返回标题类型
            if (categoryIndex == 0) {
                return TYPE_CATEGORY_ITEM;
            }
            //如果是子项返回子项类型
            if (categoryIndex > 0  && categoryIndex < size - 1) {
                return TYPE_ITEM;
            }
            categoryFirstIndex += size;
        }
        return TYPE_ITEM;
    }

    /**
     * 获取所有分类的Item的总数
     */
    @Override
    public int getItemCount() {
        int count = 0;
        if (null != hierarchyDataSet) {
            // 所有分类中item的总和是ListVIew Item的总个数
            List<ESPRowSet> oneLevelRowSetList = hierarchyDataSet.getRowSetList();
            if (oneLevelRowSetList == null ) return count;
            for (ESPRowSet espRowSet : oneLevelRowSetList) {
                EFRowSet oneLevelRowSet = (EFRowSet) espRowSet;
                Map<String, EFDataSet> twoLevelDataSetMap = oneLevelRowSet.getDataSetMap();
                if (twoLevelDataSetMap == null || twoLevelDataSetMap.size() == 0) continue;
                //取出twoLevelDataSetMap中唯一的DataSet
                EFDataSet twoLevelDataSet = twoLevelDataSetMap.get(twoLevelDataSetMap.keySet().iterator().next());
                count += CommodityDataManager.getItemCount(twoLevelDataSet);
            }
        }
        return count;
    }

    /**
     * 获取Item
     */
    public EFRowSet getItem(int position) {
        // 异常情况处理
        if (null == hierarchyDataSet || position < 0 || position > getItemCount()) {
            return null;
        }
        // 同一分类内，第一个元素的索引值
        int categoryFirstIndex = 0;
        List<ESPRowSet> oneLevelRowSetList = hierarchyDataSet.getRowSetList();
        if (oneLevelRowSetList == null ) return null;
        for (ESPRowSet espRowSet : oneLevelRowSetList) {
            EFRowSet oneLevelRowSet = (EFRowSet) espRowSet;
            Map<String, EFDataSet> twoLevelDataSetMap = oneLevelRowSet.getDataSetMap();
            if (twoLevelDataSetMap == null || twoLevelDataSetMap.size() == 0) continue;
            //取出twoLevelDataSetMap中唯一的DataSet
            EFDataSet twoLevelDataSet = twoLevelDataSetMap.get(twoLevelDataSetMap.keySet().iterator().next());

            int size = CommodityDataManager.getItemCount(twoLevelDataSet);
            // 在当前分类中的索引值
            int categoryIndex = position - categoryFirstIndex;
            // item在当前分类内
            if (categoryIndex < size) {
                return CommodityDataManager.getItem(twoLevelDataSet,categoryIndex);
            }
            // 索引移动到当前分类结尾，即下一个分类第一个元素索引
            categoryFirstIndex += size;
        }
        return null;
    }



    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        RecyclerView.ViewHolder holder = null;
        //获取指定位置的Item的类型
        switch (viewType) {
            //如果是标题类型, 则填充标题布局
            case TYPE_CATEGORY_ITEM:
                view = mInflater.inflate(R.layout.category_commodity_item_header, parent, false);
                holder = new HeaderViewHolder(view);
                break;
            //如果是子项类型则填充子项的布局
            case TYPE_ITEM:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_commodity_item, parent, false);
                holder = new ItemViewHolder(view);
                break;
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        //处理ColumnModel各种null的情况
        ColumnModel columnModel = commodity.getColumnModel();
        if (columnModel == null || columnModel.getChildren() == null || columnModel.getChildren().size() == 0) return;
        final ColumnGroup columnGroup = (ColumnGroup) commodity.getColumnModel().getChildren().get(0);
        if (columnGroup == null || columnGroup.getChildren()==null || columnGroup.getChildren().size() == 0) return;
        final List<DataComponent> columnList = columnModel.getChildren().get(0).getChildren();
        switch (holder.getItemViewType()){
            //如果是标题类型, 处理标题布局
            case TYPE_CATEGORY_ITEM:
                final HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
                final EFRowSet headerRowSet = (EFRowSet) getItem(position);
                headerViewHolder.textView.setText(headerRowSet.getString(columnGroup.getDataSetColID(),""));
                headerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("--","点击的位置：" + position);
                    }
                });
                break;
            //如果是子项类型，处理子项的布局
            case TYPE_ITEM:
                final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
                // 绑定数据
                final EFRowSet rowSet = (EFRowSet) getItem(position);
                if (rowSet == null) {
                    System.out.println("rowSet==null");
                    return;
                }
                for (int i=0 ; i<columnList.size() ; i++){
                    Column column = (Column) columnList.get(i);
                    if ("name".equals(column.getComponentType())){
                        itemViewHolder.name.setDataSetID(column.getDataSetID());
                        itemViewHolder.name.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.name.setDataSetComponent(commodity.getDataSetComponent());
                        itemViewHolder.name.dataChanged(rowSet.getDataSet());
                    }else if ("price".equals(column.getComponentType())){
                        if (column.isVisible()){
                            itemViewHolder.priceContainer.setVisibility(View.VISIBLE);
                        }else {
                            itemViewHolder.priceContainer.setVisibility(View.INVISIBLE);
                        }
                        itemViewHolder.price.setDataSetID(column.getDataSetID());
                        itemViewHolder.price.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.price.setDataSetComponent(commodity.getDataSetComponent());
                        itemViewHolder.price.dataChanged(rowSet.getDataSet());
                    }else if ("description".equals(column.getComponentType())){
                        itemViewHolder.description.setDataSetID(column.getDataSetID());
                        itemViewHolder.description.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.description.setDataSetComponent(commodity.getDataSetComponent());
                        itemViewHolder.description.dataChanged(rowSet.getDataSet());
                    }else if ("icon".equals(column.getComponentType())){
                        itemViewHolder.icon.setDataSetID(column.getDataSetID());
                        itemViewHolder.icon.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.icon.setDataSetComponent(commodity.getDataSetComponent());
                        itemViewHolder.icon.setImageName(column.getImageName());
                        itemViewHolder.icon.setImageUrlPrefix(column.getImageUrlPrefix());
                        itemViewHolder.icon.setDefaultImageLoadMode(column.getDefaultImageLoadMode());

                        itemViewHolder.icon.dataChanged(rowSet.getDataSet());
                    }else if ("actionIcon".equals(column.getComponentType())){
                        itemViewHolder.shoppingButton.setDataSetID(column.getDataSetID());
                        itemViewHolder.shoppingButton.setDataSetColID(column.getDataSetColID());
                        itemViewHolder.shoppingButton.setDataSetComponent(commodity.getDataSetComponent());
                        itemViewHolder.shoppingButton.setImageName(column.getImageName());
                        itemViewHolder.shoppingButton.setImageUrlPrefix(column.getImageUrlPrefix());
                        itemViewHolder.shoppingButton.setDefaultImageLoadMode(column.getDefaultImageLoadMode());

                        itemViewHolder.shoppingButton.dataChanged(rowSet.getDataSet());
                    }
                }
                itemViewHolder.shoppingButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //??? FIXME 点击后直接派发事件，然后ArcMenu监听数据变化，更新数据（数据驱动）
                        ShoppingCarFormModel shoppingCarFormModel = commodity.getShoppingCarFormModel();
                        if (shoppingCarFormModel == null) return;
                        if (commodity.getColumnModel() == null || commodity.getColumnModel().getChildren() == null) return;

                        EFRowSet headerRowSet = rowSet.getDataSet().getParentRowSet();
                        String headerColID = columnGroup.getDataSetColID();
                        if (headerRowSet == null) return;
                        String headerName = headerRowSet.getString(headerColID,"");

                        //3.加入到购物车模型中
                        EFDataSet shoppingCarDataSet = shoppingCarFormModel.getFormDataModel().getDataSet(headerName);
                        if(shoppingCarDataSet == null) {
                            shoppingCarDataSet = new EFDataSet();
                            shoppingCarDataSet.setTableName(headerName);
                            shoppingCarFormModel.getFormDataModel().setDataSet(headerName, shoppingCarDataSet);
                        }else {////判断购物车中是否存在该商品,如果存在直接return
                            List<ESPRowSet> shoppingCarRowSetList = shoppingCarDataSet.getRowSetList();
                            if (shoppingCarRowSetList != null){
                                for (ESPRowSet tempCarRowSet:shoppingCarRowSetList){
                                    EFRowSet shoppingCarRowSet = (EFRowSet) tempCarRowSet;
                                    if (rowSet.getDataMap() == shoppingCarRowSet.getDataMap()){
                                        Toast.makeText(commodity.getContext(),ResStringUtil.getString(R.string.mail_good_join_car),Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                }
                            }
                        }
                        transformRowSet(rowSet,columnList);
                        //rowSet克隆（重新 new 一个 RowSet）
                        EFRowSet cloneRowSet = new EFRowSet();
                        cloneRowSet.setRowSelected(true);
                        cloneRowSet.setDataMap(rowSet.getDataMap());
//                        dataSet.insertRowSet(rowSet);
                        shoppingCarDataSet.addRowSet(cloneRowSet);
                        //处理shoppingCar
                        shoppingCarFormModel.dataSetChanged(new DataSetEvent(shoppingCarDataSet,DataSetEvent.UPDATE));

//                        FragmentActivity currentActivity = (FragmentActivity) EFFrameUtils.getCurrentActivity();
////                        EFAppAccountTabFragmentInterface tabFragmentInterface = (EFAppAccountTabFragmentInterface) currentActivity.getSupportFragmentManager().findFragmentByTag(EFAppAccountMainActivityFragmentManager.FRAGMENT_TAG_PREFIX + 0);
////                        EFArcMenuSuperScriptItem arcMenuItem = (EFArcMenuSuperScriptItem) tabFragmentInterface.getArcMenu().getItem(0);
//////                        EFArcMenuSuperScriptItem arcMenuItem = (EFArcMenuSuperScriptItem) ArcMenuList.arcMenuList.get(0).getItem(0);
////                        arcMenuItem.superscriptAddNumber(1);
                        //1.获取ArcMenu
                        ArcMenu arcMenu = commodity.getArcMenu();
                        EFArcMenuSuperScriptItem arcMenuItem = (EFArcMenuSuperScriptItem) arcMenu.getItem(0);
                        if (arcMenuItem == null ) return;
                        arcMenuItem.superscriptAddNumber(1);

                        //2.抛物线动画
//                        CircleTextView circleTextView = new CircleTextView(v.getContext());
//                        circleTextView.setBackgroundColor(ResourcesCompat.getColor(v.getResources(),R.color.ef_red,null));
//                        new ParabolaAnimationUtils(currentActivity).playParabolaAnimation(circleTextView,v,arcMenuItem);
                        FormParabolaAnimation formParabolaAnimation =  new FormParabolaAnimation();
                        formParabolaAnimation.setBackgroundColor(0xFFFF0000);
                        formParabolaAnimation.playParabolaAnimation(v,arcMenuItem);


                    }
                });

                itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("--","点击的位置：" + position);
                    }
                });

                break;
        }

    }

    /**
     * 根据column的配置，使RowSet有key=componentType，value = rowSet.get(dataSetColID)的列
     * @param rowSet
     * @return
     */
    private EFRowSet transformRowSet(EFRowSet rowSet,List<DataComponent> columnList){
        for (int i=0 ; i<columnList.size() ; i++){
            Column column = (Column) columnList.get(i);
            Object componentTypeValue = rowSet.getObject(column.getComponentType(),null);
            if (componentTypeValue == null){
                rowSet.putObject(column.getComponentType(),rowSet.getObject(column.getDataSetColID(),null));
            }
        }
        return rowSet;
    }


    @Override
    public long getItemId(int position) {
        return position;
    }



    private class HeaderViewHolder extends RecyclerView.ViewHolder{
        TextView textView;
        public HeaderViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.co_header_tv);
        }
    }
    private class ItemViewHolder extends RecyclerView.ViewHolder{
        FormLabel name;
        FormLabel description;
        FormLabel price;
        LinearLayout priceContainer;
        FormImage icon;
        FormImage shoppingButton;
        public ItemViewHolder(View itemView) {
            super(itemView);
            name = (FormLabel) itemView.findViewById(R.id.co_name);
            description = (FormLabel) itemView.findViewById(R.id.co_description);
            price = (FormLabel) itemView.findViewById(R.id.co_price);
            priceContainer = (LinearLayout) itemView.findViewById(R.id.price_container);
            icon = (FormImage) itemView.findViewById(R.id.co_imageView);
            shoppingButton = (FormImage) itemView.findViewById(R.id.button_shopping);
        }
    }
}